package com.zlz.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zlz.server.annotation.OperateLog;
import com.zlz.server.constant.RoleConstant;
import com.zlz.server.pojo.MenuRole;
import com.zlz.server.pojo.RespBean;
import com.zlz.server.pojo.Role;
import com.zlz.server.service.IMenuRoleService;
import com.zlz.server.service.IMenuService;
import com.zlz.server.service.IRoleService;
import com.zlz.server.enums.OprLevel;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zlz
 * @date: 2021/1/24 20:40
 * @description:
 * @since: JDK1.8
 */
@RestController
@RequestMapping("/system/basic/permission")
public class PermissionController {
    @Resource
    private IRoleService iRoleService;

    @Resource
    private IMenuService iMenuService;

    @Resource
    private IMenuRoleService iMenuRoleService;

    @ApiOperation(value = "获取角色信息")
    @GetMapping("/")
    public List<Role> getAllRoles() {
        return iRoleService.list();
    }

    @ApiOperation(value = "添加角色")
    @PostMapping("/role")
    @OperateLog(operationName = "添加角色", moduleName = "角色", level = OprLevel.LOW)
    public RespBean addRole(@RequestBody Role role) {
        String name = role.getName();
        if (!name.startsWith(RoleConstant.PREFIX_ROLE)) {
            role.setName(RoleConstant.PREFIX_ROLE + name);
        }
        if (iRoleService.save(role)) {
            return RespBean.success("添加成功", null);
        }
        return RespBean.error("添加失败");
    }

    @ApiOperation(value = "删除角色信息")
    @DeleteMapping("/{rid}")
    @OperateLog(operationName = "删除角色", moduleName = "角色", level = OprLevel.HIGH)
    public RespBean delRole(@PathVariable("rid") Long id) {
        if (iRoleService.removeById(id)) {
            return RespBean.success("删除成功", null);
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation(value = "获取菜单信息")
    @GetMapping("/menus")
    public RespBean getAllMenus() {
        return RespBean.success(iMenuService.getAllMenus());
    }

    @ApiOperation(value = "根据角色获取菜单信息")
    @GetMapping("/mid/{rid}")
    public RespBean getAllMenus(@PathVariable Long rid) {
        return RespBean.success(iMenuRoleService.list(new QueryWrapper<MenuRole>().eq("role_id", rid)).stream()
                .map(MenuRole::getMenuId)
                .collect(Collectors.toList())
        );
    }

    @ApiOperation(value = "更新角色菜单")
    @PutMapping("/")
    @OperateLog(operationName = "更新角色菜单", moduleName = "角色", level = OprLevel.NORMAL)
    public RespBean updateMenuRole(Long rid, Long[] mids) {
        return iMenuRoleService.updateMenuRole(rid, mids);
    }
}
